package model

import (
	"context"
	"fmt"
	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/mongo/options"
	. "leaf/cache"
	"leaf/core/log"
	"leaf/core/tool"
)

const (
	DEFAULT_USERID = 10000000
)

var docmentIdMap = map[string][]string{
	GLOBAL_USERID: {"game", "user", "userid", fmt.Sprintf("%v", DEFAULT_USERID)},
}

func LoadData() {
	LoadDocmentId()
	LoadGameInfo()
}

//加载最大id值
func LoadDocmentId() {
	log.Release("load docment id...")
	var cache = GetCache()
	if cache == nil {
		panic("load docment id error:cache is nil")
		return
	}

	var mgo = GetMongo()
	if mgo == nil {
		panic("load docment id error:mgo is nil")
		return
	}

	for key, val := range docmentIdMap {
		var col = mgo.Database(val[0]).Collection(val[1])
		pipeline := []bson.M{
			bson.M{"$group": bson.M{"_id": "null", "max": bson.M{"$max": "$" + val[2]}}},
		}

		var id = tool.AtoUint64(val[3])
		var cur, _ = col.Aggregate(context.TODO(), pipeline, options.Aggregate())
		if cur.Next(context.TODO()) {
			var doc map[string]interface{}
			cur.Decode(&doc)
			id = tool.AtoUint64(fmt.Sprintf("%v", doc["max"]))
		}
		cache.Set(tool.RdKey(key, GetKeyPrefix()), id, 0)
		log.Release("%v.%v.%v = %v", val[0], val[1], val[2], id)
	}
}

//加载游戏信息数据
func LoadGameInfo() {
	var cache = GetCache()
	if cache == nil {
		panic("load docment id error:cache is nil")
		return
	}

	var mgo = GetMongo()
	if mgo == nil {
		panic("load docment id error:mgo is nil")
		return
	}

	var col = mgo.Database("game").Collection("gameinfo")
	cur, _ := col.Find(context.TODO(), bson.M{})
	if cur.Next(context.TODO()) {
		var doc map[string]interface{}
		cur.Decode(&doc)
		key := tool.RdKey(GLOBAL_GAMEINFO, GetKeyPrefix(), doc["key"])
		cache.Set(key, doc["val"], 0)
		log.Release("%v = %v", key, doc["val"])
	}

}
